import React,{useState,useEffect} from 'react';
import {Card,Button,Modal} from 'antd';
import {useNavigate} from 'react-router-dom';
import api from '../api'
import {scanQRCodePay} from '../helpers';
function Products(){
    const navigate = useNavigate();
    const [products,setProducts] = useState([]);
    const fetchProducts = ()=>{
        api.get('/api/products').then(response=>{
            setProducts(response.data);
        })
    }
    useEffect(fetchProducts,[]);
    const handleBuy = async (product)=>{
        try{
            const response = await api.get(`/api/payment/native/${product.id}`);
            const {orderNo,code_url} = response.data;
            console.log('orderNo',orderNo,'code_url',code_url);
            scanQRCodePay({orderNo,code_url,callback:()=>navigate('/orders')});
        }catch(error){
            console.log(`下单失败`,error);
            Modal.error({
                title:'错误',
                content:'无法下单，请稍后重试'
            })
        }
    }
    return (
        <>
          {
            products.map(product=>(
                <Card
                 key={product.id}
                 style={{width:240,float:'left',margin:'16px'}}
                 hoverable
                 cover={<img src={product.cover}/>}
                 actions={[<Button type='primary' onClick={()=>handleBuy(product)}>购买</Button>]}
                >
                    <Card.Meta title={product.name} 
                    description={`价格: ￥${(product.price / 100).toFixed(2)}`}></Card.Meta>
                </Card>
            ))
          }
        </>
    )
}
export default Products;